package com.baturu.vin.gm.service.impl;

import com.baturu.vin.base.service.EPCCacheRealTimeProcess;
import com.baturu.vin.gm.dal.dao.VinModelDAO;
import com.baturu.vin.gm.dto.ResponseCarDTO;
import com.baturu.vin.gm.dto.GMVinModelDTO;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Slf4j
@Service("generalMotorsEPCCacheRealTimeProcess")
public class GeneralMotorsEPCCacheRealTimeProcess implements EPCCacheRealTimeProcess {

    @Autowired
    private VinModelDAO vinModelDAO;

    @Override
    public boolean buildVinAnalyticalResults(String vinCode, String analyticalResults) {
        GMVinModelDTO vinModelDTO = buildQueryCarResult(vinCode, analyticalResults);
        if (!Objects.isNull(vinModelDTO)) {
            saveVinModel(vinModelDTO);
        }
        return true;
    }

    private int saveVinModel(GMVinModelDTO vinModelDTO) {
        String vinCode = vinModelDTO.getVinCode();
        GMVinModelDTO model = vinModelDAO.findVinModel(vinCode);
        if (Objects.isNull(model)) {
            return vinModelDAO.insert(vinModelDTO);
        }
        return 0;
    }

    private GMVinModelDTO buildQueryCarResult(String vinCode, String result) {
        GMVinModelDTO vinModelDTO = null;
        try {
            if (StringUtils.isBlank(result)) {
                return null;
            }
            Gson gson = new Gson();
            ResponseCarDTO responseCarDTO = gson.fromJson(result, ResponseCarDTO.class);
            if (Objects.isNull(responseCarDTO)) {
                return null;
            }
            String status = responseCarDTO.getStatus();
            if (StringUtils.equals("ok", status)) {
                vinModelDTO = responseCarDTO.getVininfo();
            }
        } catch (Exception e) {
            log.error("vin {} 查询结果转换异常:{}", vinCode, e);
        }
        return vinModelDTO;
    }

}
